/***************************************************************************
*   Copyright (C) 2005 by Alexander Nemish  *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   You should have received a copy of the GNU General Public License     *
*   along with this program; if not, write to the                         *
*   Free Software Foundation, Inc.,                                       *
*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
***************************************************************************/
#include <qpainter.h>
#include <qevent.h>
#include <qimage.h>
#include <kdebug.h>
#include <kprogress.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qtextcodec.h>
#include <qstring.h>
#include "bookwidget.h"
#include "theme.h"
#include "settings.h"
#include "renderer.h"
//#include "ktextprogressdlg.h"

class QStringList;
class QRect;
class QPixmap;

BookWidget::BookWidget(QWidget *parent, const char *name)
		: QWidget(parent, name),
		m_currentPage(0),
		m_left_margin(0),
		m_right_margin(0),
		m_top_margin(0),
		m_bottom_margin(0),
		m_middle_margin(0),
		m_renderer(new Renderer())
{
	//setupPageSize();
	//setupSlots();
	m_left_margin = 30;
	m_right_margin = 30;
	m_top_margin = 20;
	m_bottom_margin = 15;
	m_middle_margin = 20;

	setFont(Settings::font());

	Theme::self()->loadTheme("default");

	QPixmap & image = Theme::self()->bgPixmap();
	image.convertFromImage(image.convertToImage().scale(size()));

	setWFlags(Qt::WNoAutoErase);
	setFocusPolicy(QWidget::StrongFocus);
	//m_process = new TextProcessDialog(this);
	//m_thread = new TextThread(this);
	//connect( m_renderer, SIGNAL( loaded(int) ), this, SIGNAL( loaded(int) ) );
}


BookWidget::~BookWidget()
{
}

void BookWidget::openURL(const KURL & url)
{
	m_currentPage = 0;
	m_url = url;
	QFile file(url.path());
	//QFile file( m_file );
	//TODO: Do for urls
	if (file.open(IO_ReadOnly) == false)
		return ;

	///@todo Write encoding detection
	QTextStream stream(&file);
	QStringList strList;
	QTextCodec *codec = QTextCodec::codecForName("CP1251"); // get the codec for KOI8-R
	stream.setCodec(codec);
	//QString unicodeString = codec->toUnicode( locallyEncoded );
	while (!stream.eof())
		strList += stream.readLine(); // + "\n";

	file.close();

	// now that we have the entire file, display it
	m_renderer->load(strList);

	// just for fun, set the status bar
	emit signalChangeStatusbar(m_url.prettyURL());
}

QString BookWidget::currentURL()
{
	return m_url.path();
}

void BookWidget::paintEvent(QPaintEvent*)
{
	setupPageSize();
	const QRect lrect (m_left_margin, m_top_margin,
	                    m_renderer->pageSize().width(),
	                    m_renderer->pageSize().height());
	const QRect rrect(m_left_margin + 2 * m_middle_margin + lrect.width(),
	                   m_top_margin,
	                   m_renderer->pageSize().width(),
	                   m_renderer->pageSize().height());

	QPixmap pm(size());
	//kdDebug() << "pain m_lines count = " << m_lines.count() << endl;
	QPainter paint(&pm);
	QPixmap & image = Theme::self()->bgPixmap();
	paint.drawPixmap(0, 0, image);

	QFontMetrics fm(font());

	paint.setFont(font());

	m_renderer->drawPage(paint, lrect, m_currentPage);
	m_renderer->drawPage(paint, rrect, m_currentPage + 1);

	QFont pageFont(font());
	int pointSize = (font().pointSize() > 10) ? font().pointSize() - 2 : 10;
	pageFont.setPointSize(pointSize);
	pageFont.setBold(false);
	pageFont.setItalic(false);
	pageFont.setUnderline(false);
	paint.setFont(pageFont);

	if (!m_renderer->isEmpty())
	{
		QString number = (QString::number(m_currentPage + 2));
		QFontMetrics fm(pageFont);

		int width = fm.width(number);
		int height = fm.height();

		//paint page numbers
		paint.drawText(lrect.left(), QWidget::height() - 5,
		                QString::number( m_currentPage + 1 ));
		paint.drawText(rrect.left() + rrect.width() - width,
		                QWidget::height() - 5, number);
	}

	paint.end();
	bitBlt(this, 0, 0, &pm);
}


void BookWidget::setupPageSize()
{
	m_renderer->setPageSize(QSize((width() - m_left_margin - m_right_margin -
	                               2 * m_middle_margin) / 2,
	                              (height() - m_top_margin - m_bottom_margin)));
}

void BookWidget::mousePressEvent(QMouseEvent * event)
{
	if (event->button() == LeftButton)
	{
		if (rectLeftPage().contains(event->pos()))
		{
			prevPage();
		}
		else if (rectRightPage().contains(event->pos()))
		{
			nextPage();
		}
	}
	QWidget::mousePressEvent(event);
}

const QRect BookWidget::rectLeftPage() const
{
	return QRect(m_left_margin, m_top_margin,
	              m_renderer->pageSize().width(),
	              m_renderer->pageSize().height());
}

const QRect BookWidget::rectRightPage() const
{
	return QRect(m_left_margin + 2 * m_middle_margin + m_renderer->pageSize().width(),
	              m_top_margin,
	              m_renderer->pageSize().width(),
	              m_renderer->pageSize().height());
}

void BookWidget::clearAll()
{
	m_currentPage = 0;
}


void BookWidget::prevPage()
{
	if ((m_currentPage - 2) >= 0)
	{
		m_currentPage -= 2;
		update();
	}
}

void BookWidget::nextPage()
{
	if (m_currentPage + 2 <= m_renderer->pageCount())
	{
		m_currentPage += 2;
		update();
	}
}

void BookWidget::firstPage()
{
	m_currentPage = 0;
	update();
}

void BookWidget::lastPage()
{
	int pageCount = m_renderer->pageCount();
	m_currentPage = pageCount - (pageCount & 1);
	update();
}

void BookWidget::wheelEvent(QWheelEvent * e)
{
	e->accept();
	if (e->delta() > 0)
		prevPage();
	else nextPage();
}


void BookWidget::resizeEvent(QResizeEvent * e)
{
	kdDebug() << "resizeEvent, size(" << e->size() << ")" << endl;
	kdDebug() << "old size(" << e->oldSize() << ")" << endl;
	setupPageSize();
	//if size become lower recalc current page
	if (m_currentPage > m_renderer->pageCount())
		m_currentPage = m_renderer->pageCount() - (m_renderer->pageCount() % 2);
	//resize bg image;
	QPixmap & image = Theme::self()->bgPixmap();
	image.convertFromImage(image.convertToImage().scale(size()));
	m_renderer->render();
	QWidget::resizeEvent(e);
}

QSize BookWidget::minimumSizeHint() const
{
	return QSize(400, 300);
}

void BookWidget::setFont(const QFont & font)
{
	QWidget::setFont(font);
	m_renderer->setFont(font);
	update();
}

void BookWidget::setCurrentPage(int number)
{
	if (number < 0) number = 0;
	
	m_currentPage = (number >= m_renderer->pageCount()) ? 
                    (m_renderer->pageCount() - 1) : number;
	update();
}

void BookWidget::keyPressEvent( QKeyEvent * e )
{
	kdDebug() << "key pressed " << endl;
	if (e->key() == Qt::Key_Right || e->key() == Qt::Key_Down 
		|| e->key() == Qt::Key_Space)
	{
		nextPage();
	}
	else if (e->key() == Qt::Key_Left || e->key() == Qt::Key_Up)
	{
		prevPage();
	}
	else if (e->key() == Qt::Key_Home)
	{
		firstPage();
	}
	else if (e->key() == Qt::Key_End)
	{
		lastPage();
	}

	QWidget::keyPressEvent(e);
}

#include "bookwidget.moc"
